package com.baidu.videoseries.service;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;

import com.baidu.videoseries.MainActivity;
import com.baidu.videoseries.R;
import com.baidu.videoseries.bean.MediaBean;
import com.baidu.videoseries.constant.Config;
import com.baidu.videoseries.receiver.MusicReceiver;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

public class MusicService extends Service implements OnErrorListener, OnPreparedListener, MediaPlayer.OnCompletionListener {

    private static final String TAG = "MusicService";
    private static final int NOTIFICATION_ID = 21;
    private MediaPlayer mMediaPlayer;
    private WifiManager.WifiLock mWifiLock;
    private String audioPath;
    private NotificationCompat.Builder builder;
    private NotificationManager manager;
    private Timer mTimer;

    private MusicReceiver mReceiver;
    private ArrayList<MediaBean> mPlayData;
    private int cursorIndex = 0;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent.getAction().equals(Config.MediaAction.ACTION_AUDIO_PLAYER)) {
            this.mReceiver = new MusicReceiver();
            registerReceiver(mReceiver, new IntentFilter(Config.MediaAction.ACTION_COMMAND));
            this.mReceiver.setOnReceiveListener(mCommandReceiver);
            this.mPlayData = new ArrayList<>();
            initMediaPlayer();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * init media player
     */
    private void initMediaPlayer() {
        //check whether playlist is empty
        if (mPlayData.size() < 1) return;
        //check cursorIndex included in area[0,mPlayData.size()]
        cursorIndex = cursorIndex >= mPlayData.size() ? 0 : cursorIndex;
        cursorIndex = cursorIndex < 0 ? (mPlayData.size() - 1) : cursorIndex;
        String url = mPlayData.get(cursorIndex).getLocalPath();
        if (TextUtils.isEmpty(url)) {
            cursorIndex++;
            initMediaPlayer();
            return;
        }

        if (mMediaPlayer == null) {
            mMediaPlayer = new MediaPlayer();
            mWifiLock = ((WifiManager) getSystemService(WIFI_SERVICE))
                    .createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");
            mWifiLock.acquire();
            mMediaPlayer.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK);//play with permission when the cellphone is locked
        }
        mMediaPlayer.reset();
        mMediaPlayer.setOnErrorListener(this);
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnCompletionListener(this);
//        initPendingIntent(audioPath);
        try {
            mMediaPlayer.setDataSource(url);
            mMediaPlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void initPendingIntent(String audioPath, MediaPlayer mPlayer) {
        if (TextUtils.isEmpty(audioPath) || mPlayer == null) return;
        String songName = audioPath.substring(audioPath.lastIndexOf("/") + 1, audioPath.length());

        PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0,
                new Intent(getApplicationContext(), MainActivity.class),
                PendingIntent.FLAG_UPDATE_CURRENT);
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        builder = new NotificationCompat.Builder(this)
                .setTicker("didi")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(songName)
                .setAutoCancel(true)
                .setOnlyAlertOnce(true)
//                .setOngoing(true)
                .setContentInfo("MusicPlayer")
                .setProgress(mPlayer.getDuration(), mPlayer.getCurrentPosition(), false)
                .setContentIntent(pi);
        manager.notify(NOTIFICATION_ID, builder.build());
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        return false;
    }

    @Override
    public void onPrepared(final MediaPlayer mp) {
        mp.start();
        sendStatus(Config.Status.START);
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (mp == null) mTimer.cancel();
                initPendingIntent(audioPath, mp);
//                LogUtils.e("position=" + mp.getCurrentPosition());
                builder.setProgress(mp.getDuration(), mp.getCurrentPosition(), false);
                manager.notify(NOTIFICATION_ID, builder.build());
                Intent intent = new Intent().setAction(Config.MediaAction.ACTION_PREPARED);
                intent.putExtra(Config.Key.PROGRESS, mp.getCurrentPosition() * 100 / mp.getDuration());
//                intent.putExtra(Key.MUSIC_LENGTH, mp.getDuration());
                sendBroadcast(intent);
//                builder.mNotification
            }
        }, 0, 1000);
    }

    /**
     * response
     */
    private void sendStatus(int response) {
        Intent mIntent = new Intent(Config.MediaAction.ACTION_RESPONSE);
        mIntent.putExtra(Config.Key.STATUS, response);
        sendBroadcast(mIntent);
    }


    @Override
    public void onDestroy() {

        if (mWifiLock != null) {
            mWifiLock.release();
            mWifiLock = null;
        }

        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }

        unregisterReceiver(mReceiver);
        super.onDestroy();
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        cursorIndex++;
        initMediaPlayer();
    }

    /**
     * on receiver listener
     */
    private MusicReceiver.OnReceiverListener mCommandReceiver = new MusicReceiver.OnReceiverListener() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null) return;
            if (!intent.getAction().equals(Config.MediaAction.ACTION_COMMAND)) return;
            int command = intent.getIntExtra(Config.Key.COMMAND, -1);
            switch (command) {
                case Config.Command.PLAY:
                    if (mMediaPlayer.isPlaying()) {
                        mMediaPlayer.pause();
                        sendStatus(Config.Status.PAUSE);
                    }
                    if (!mMediaPlayer.isPlaying()) {
                        mMediaPlayer.start();
                        sendStatus(Config.Status.PLAYING);
                    }
                    break;
                case Config.Command.NEXT:
                    cursorIndex++;
                    initMediaPlayer();
                    break;
                case Config.Command.PREVIOUS:
                    cursorIndex--;
                    initMediaPlayer();
                    break;
                case Config.Command.CURSOR_INDEX:
                    cursorIndex = intent.getIntExtra(Config.Key.CURSOR_INDEX, 0);
                    initMediaPlayer();
                    break;
                case Config.Command.DATA_CHANGED:
                    initPlayList(intent);
                    break;
                case Config.Command.PROGRESS_CHANGED:
                    int p = intent.getIntExtra(Config.Key.PROGRESS, 0);
                    mMediaPlayer.seekTo(p);
                    mMediaPlayer.start();
                    break;
            }
        }
    };

    /**
     * init plat list
     *
     * @param intent
     */
    private void initPlayList(Intent intent) {
        if (intent == null) return;
        if (mPlayData.size() > 0) mPlayData.clear();
        ArrayList<MediaBean> list = intent.getParcelableArrayListExtra(Config.Key.FILE_LIST);
        MediaBean bean = intent.getParcelableExtra(Config.Key.FILE);
        if (list != null) mPlayData.addAll(list);
        if (bean != null) mPlayData.add(bean);

        this.cursorIndex = 0;
    }
}
